from django.shortcuts import render
from django.http import HttpResponse
from dashboard.models import *
import time,os

#上传图片专用
def pic_upload(request):
	#判断用户是否上传文件
    myfile = request.FILES.get('head_img',None)
    if not myfile:
        return 'default.jpg'

    #执行上传处理
    filename = str(round(time.time()))+'.'+myfile.name.split('.').pop()

    #打开文件
    destination = open("./static/dash/pics/"+filename,"wb+")
    for chunk in myfile.chunks():      #分块写入文件  
       destination.write(chunk)  
    #关闭文件
    destination.close()
    return filename

#获取分类函数
def type_get():
	typee = Types.objects.filter(pid = 0)
	for v in typee:
		v.sub = Types.objects.filter(pid = v.id)
		for vv in v.sub:
			vv.goods_info = Goods.objects.filter(typeid = vv.id)
	return typee



#####登录部分#####
#访问登录页面
def login_page(request):
	return render(request,'web/login.html')

#执行用户登录
def do_login(request):
	#判断验证码
	if request.session['verifycode'] != request.POST['verifycode'].upper():
		return HttpResponse('<script>alert("验证码错误");location.href="/web/login";</script>')
		
	#判断登录信息是否正确
	try:
		user = Users.objects.get(username = request.POST['username'])
		#判断用户权限是否为普通用户
		if user.state == 1:
			from django.contrib.auth.hashers import make_password, check_password
			#判断用户密码是否正确
			if check_password(request.POST['password'],user.pwd):
				#用户信息存入session
				request.session['web_user_info'] = {'user_id':user.id,'user_name':user.username,'user_hdimg':user.head_img}
				#跳转至dashboard index page
				return HttpResponse('<script>alert("登陆成功");location.href="/web/index";</script>')
			else:
				return HttpResponse('<script>alert("用户名密码错误");location.href="/web/login";</script>')
		elif user.state == 2:
			return HttpResponse('<script>alert("该用户已被封停");location.href="/web/login";</script>')
		else:
			return HttpResponse('<script>alert("用户不存在");location.href="/web/login";</script>')
	except:
		return HttpResponse('<script>alert("用户名或密码错误");location.href="/web/login";</script>')

#访问注册页面
def register_page(request):
	return render(request,'web/register.html')

#执行注册
def do_register(request):
	#引入加密模块
	from django.contrib.auth.hashers import make_password,check_password
	try:
		#实例一个user对象 并存入属性
		user = Users()
		user.username = request.POST['username']
		user.pwd = make_password(request.POST['pwd'],None,'pbkdf2_sha256')
		user.gender = request.POST['gender']
		user.address = request.POST['address']
		user.code = request.POST['code']
		user.phone = request.POST['phone']
		user.head_img = pic_upload(request)
		user.save()
		#跳转到index路由
		return HttpResponse('<script>alert("新增成功");location.href="/web/login"</script>')
	except :
		return HttpResponse('<script>alert("新增失败");location.href="/web/register"</script>')



#####商品部分#####
#访问index页面
def index_page(request):
	#获取总分类信息,购物车中的商品数量
	cart = request.session.get('cart',{})
	
	#判断购物车内商品件数
	if cart == {}:
		cart_num = 0
	else:
		cart_num = len(request.session['cart'])

	re_info = {'types':type_get(),'cart_num':cart_num}
	return render(request,'web/index.html',re_info)

#访问list列表页面
def list_page(request):
	#获取商品信息
	typee = Types.objects.filter(pid = request.GET['tid'])
	for v in typee:
		v.goods_infos = Goods.objects.filter(typeid = v.id)

	#获取总分类信息(header使用)
	re_info = {'types':type_get(),'typee':typee}
	return render(request,'web/list.html',re_info)

#访问detail详情页面
def detail_page(request):
	#获取单个商品信息
	goods = Goods.objects.get(id = request.GET['gid'])
	re_info = {'types':type_get(),'goods_info':goods}
	return render(request,'web/detail.html',re_info)

#注销登录
def do_logout(request):
	#将session置空
	request.session['web_user_info'] = ''

	return HttpResponse('<script>alert("注销成功");location.href="/web/index";</script>')



#####购物车部分#####
#购物车数据存放至session
def add_cart(request):
	goods_info = {}
	#根据goods_id获取商品信息
	goods = Goods.objects.get(id = request.POST['goods_id'])
	goods_info['goods_id'] = request.POST['goods_id']
	goods_info['goods_num'] = int(request.POST['goods_num'])
	goods_info['goods_name'] = goods.title
	goods_info['goods_price'] = goods.price
	goods_info['goods_photo'] = goods.photo_url

	#获取session中的购物车数据
	cart = request.session.get('cart',{})

	#判断购物车session中是否已经存在该商品
	if request.POST['goods_id'] in cart:
		#如果存在,直接更新商品购物车中库存
		cart[request.POST['goods_id']['num']] += int(request.POST['goods_num'])
	else:
		#如果不存在,添加商品信息至购物车
		cart[request.POST['goods_id']] = goods_info

	#将数据存回session
	request.session['cart'] = cart

	return HttpResponse('<script>alert("加入购物车成功");location.href="/web/cart";</script>')

#获取购物车页面
def cart_page(request):
	return render(request,'web/cart.html')

#清除购物车session
def clear_cart(request):
	request.session['cart'] = {}
	return HttpResponse('<script>alert("清除购物车成功");location.href="/web/cart";</script>')

#删除购物车中的单个物品
def del_cart(request):
	cart = request.session['cart']
	cart.pop(request.GET['gid'])
	request.session['cart'] = cart
	return HttpResponse('<script>alert("商品删除成功");location.href="/web/cart";</script>')

#更新购物车信息
def edit_cart(request):
	#获取GET过来的数据
	gid = request.GET['gid']
	num = int(request.GET['num'])
	#判断购买的数量
	if num < 1:
		return HttpResponse('<script>alert("购买数量不能小于1");location.href="/web/cart";</script>')
	#取出session中的数据
	cart = request.session['cart']
	cart[request.GET['gid']]['goods_num'] = num
	#将数据存回session
	request.session['cart'] = cart 
	return HttpResponse('<script>alert("数量更新成功");location.href="/web/cart";</script>')



#####订单部分#####
#获取确认订单页面
def cartconfirm_page(request):
	#判断商品信息是否存在(至少有一个)
	if request.POST.get('ids','') == '':
		return HttpResponse('<script>alert("请至少选择一个商品");location.href="/web/cart";</script>')

	#将获取到的商品ids切开存入列表
	ids = request.POST['ids'].split(',')

	#获取session中的购物车信息
	cart = request.session.get('cart',{})
	#设置默认总价
	total = 0
	#设置默认数量
	num = 0
	#在购物车session中获取确认订单信息,存入goods中
	goods = []
	for v in ids:
		goods.append(cart[v])
		total += cart[v]['goods_num'] * cart[v]['goods_price']
		num += cart[v]['goods_num']

	#拼装返回数据
	order_info = {'goods':goods,'total':total,'num':num}

	#设置订单session
	request.session['order'] = order_info

	#跳转至订单确定页
	return render(request,'web/order.html',order_info)

#创建订单
def create_order(request):
	#添加orders表信息
	try:
		orders = Orders()
		orders.uid = request.session['web_user_info']['user_id']
		orders.linkman = request.POST['username']
		orders.address = request.POST['address']
		orders.code = request.POST['code']
		orders.phone = request.POST['phone']
		orders.total = request.POST['total']
		orders.status = 0
		orders.save()
	except :
		return HttpResponse('<script>alert("请填齐收货信息");location.href="/web/cart";</script>')
		
	#获取订单session中的商品信息goods
	goods = request.session['order']['goods']

	#遍历数据,添加items表信息
	for v in goods:
		# print(v)
		items = Items()
		items.orderid = orders.id
		items.goodsid = v['goods_id']
		items.title = v['goods_name']
		items.price = v['goods_price']
		items.num = v['goods_num']
		items.goodspic = v['goods_photo']
		items.save()

        #清除购物车中已买的商品session信息
        #取出购物车session
		cart = request.session.get('cart',{})
		cart.pop(v['goods_id'])

		#购物车session从新储存
		request.session['cart'] = cart

	#跳转至支付路由
	return HttpResponse('<script>alert("订单创建成功,请支付");location.href="/web/payme?oid='+str(orders.id)+'";</script>')

#获取支付页面
def payme_page(request):
	order = Orders.objects.get(id = request.GET['oid'])
	re_info = {'order_info':order}

	return render(request,'web/payme.html',re_info)

#获取我的订单页面
def myorder_page(request):
	#根据用户id获取用户订单列表
	orders = Orders.objects.filter(uid = request.session['web_user_info']['user_id'])
	#获取订单下对应的商品
	for v in orders:
		v.sub = Items.objects.filter(orderid = v.id)

	#封装返回数据
	re_info = {'myorders':orders}

	return render(request,'web/myorder.html',re_info)
